package cn.itcast.usermanage.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.itcast.usermanage.mapper.NewUserMapper;
import cn.itcast.usermanage.mapper.UserMapper;
import cn.itcast.usermanage.pojo.EasyUIResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	//private UserMapper userMapper;
	private NewUserMapper userMapper;
	
	@Override
	public EasyUIResult queryEasyUIResult(Integer pageNum, Integer pageSize) {
		/*List<User> userList = userMapper.queryUserByPage((pageNumber-1)*pageSize,pageSize);
		EasyUIResult easyUIResult = new EasyUIResult();
		easyUIResult.setRows(userList);
		easyUIResult.setTotal(20l);*/
		
		//在查询方法调用之前,调用分页插件的静态方法,中间最好不要隔任何代码
		PageHelper.startPage(pageNum, pageSize);
		
		List<User> list = userMapper.select(null);
		//改为mapper方式
		
		
		//List<User> list = userMapper.queryUserAll();
		
		//初始化pageInfo对象,所有的分页参数都可以在该对象中获取
		PageInfo<User> pageInfo = new PageInfo<>(list);
		
		EasyUIResult easyUIResult = new EasyUIResult();
		easyUIResult.setTotal(pageInfo.getTotal());
		easyUIResult.setRows(pageInfo.getList());
		
		
		return easyUIResult;
	}

	@Override
	public void addUsers(User user1, User user2) {
		userMapper.insertSelective(user1);
		//int i = 1/0;
		userMapper.insertSelective(user2);
	}

	@Override
	public Boolean addUser(User user) {
		int count = userMapper.insertSelective(user);
		if(count >0){
			return true;
		}
		return false;
	}

	@Override
	public Boolean deleteUser(List<Object> ids) {
		Example example = new Example(User.class);
		Criteria criteria = example.createCriteria();
		criteria.andIn("id",ids);
		int count = userMapper.deleteByExample(example);
		if(count > 0){
			return true;
		}
		return false;
	}

	@Override
	public User queryById(Long id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void saveUser(User user) {
		userMapper.insertSelective(user);
	}

	@Override
	public Integer updateUser(User user) {
		user.setUpdated(new Date());
		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public Integer deleteById(Long id) {
		return userMapper.deleteByPrimaryKey(id);
	}

}
